package com.yf.exam.modules.exam.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.base.api.api.dto.PagingReqDTO;
import com.yf.base.api.exception.ServiceException;
import com.yf.base.utils.BeanMapper;
import com.yf.exam.modules.exam.dto.ExamApplyDTO;
import com.yf.exam.modules.exam.dto.request.ExamApplyAuditReqDTO;
import com.yf.exam.modules.exam.entity.ExamApply;
import com.yf.exam.modules.exam.mapper.ExamApplyMapper;
import com.yf.exam.modules.exam.service.ExamApplyService;
import com.yf.system.modules.user.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
* <p>
* 考试申请业务实现类
* </p>
*
* @author 聪明笨狗
* @since 2022-12-15 15:57
*/
@Service
public class ExamApplyServiceImpl extends ServiceImpl<ExamApplyMapper, ExamApply> implements ExamApplyService {

    @Override
    public IPage<ExamApplyDTO> paging(PagingReqDTO<ExamApplyDTO> reqDTO) {

        //查询条件
        QueryWrapper<ExamApply> wrapper = new QueryWrapper<>();

        // 请求参数
        ExamApplyDTO params = reqDTO.getParams();

        if(params!=null){
            if(params.getAuditState()!=null){
                wrapper.lambda().eq(ExamApply::getAuditState, params.getAuditState());
            }

            if(StringUtils.isNotBlank(params.getExamId())){
                wrapper.lambda().eq(ExamApply::getExamId, params.getExamId());
            }
        }

        wrapper.lambda().orderByDesc(ExamApply::getApplyTime);

        //获得数据
        IPage<ExamApply> page = this.page(reqDTO.toPage(), wrapper);
        //转换结果
        IPage<ExamApplyDTO> pageData = JSON.parseObject(JSON.toJSONString(page), new TypeReference<Page<ExamApplyDTO>>(){});
        return pageData;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(ExamApplyDTO reqDTO){

        // 填充数据
        reqDTO.setApplyUser(UserUtils.getUserId());
        reqDTO.setApplyTime(new Date());
        reqDTO.setAuditState(0);

        QueryWrapper<ExamApply> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ExamApply::getApplyUser, reqDTO.getApplyUser())
                .eq(ExamApply::getExamId, reqDTO.getExamId())
                .eq(ExamApply::getAuditState, 0);
        int count = this.count(wrapper);
        if(count > 0){
            throw new ServiceException("您有正在审核中的考试请求，无需重复申请！");
        }


        //复制参数
        ExamApply entity = new ExamApply();
        BeanMapper.copy(reqDTO, entity);
        this.saveOrUpdate(entity);
    }

    @Override
    public void delete(List<String> ids){
        //批量删除
        this.removeByIds(ids);
    }

    @Override
    public ExamApplyDTO detail(String id){
        ExamApply entity = this.getById(id);
        ExamApplyDTO dto = new ExamApplyDTO();
        BeanMapper.copy(entity, dto);
        return dto;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void audit(ExamApplyAuditReqDTO reqDTO) {

        ExamApply entity = new ExamApply();
        entity.setAuditBy(UserUtils.getUserId());
        entity.setAuditTime(new Date());
        entity.setAuditState(reqDTO.getAuditState());
        entity.setAuditMsg(reqDTO.getAuditMsg());
        Calendar cl = Calendar.getInstance();
        cl.setTimeInMillis(System.currentTimeMillis());
        cl.add(Calendar.MINUTE, 10);
        entity.setAuditUsed(false);

        QueryWrapper<ExamApply> wrapper = new QueryWrapper<>();
        wrapper.lambda().in(ExamApply::getId, reqDTO.getIds());

        this.update(entity, wrapper);
    }

    @Override
    public boolean pass(String userId, String examId) {
        QueryWrapper<ExamApply> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ExamApply::getApplyUser, userId)
                .eq(ExamApply::getExamId, examId)
                .eq(ExamApply::getAuditUsed, false)
                .eq(ExamApply::getAuditState, 1);

        return this.count(wrapper) > 0;
    }

    @Override
    public void useAudit(String userId, String examId) {
        QueryWrapper<ExamApply> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(ExamApply::getApplyUser, userId)
                .eq(ExamApply::getExamId, examId)
                .eq(ExamApply::getAuditUsed, false)
                .eq(ExamApply::getAuditState, 1);

        ExamApply apply = new ExamApply();
        apply.setAuditUsed(true);
        this.update(apply, wrapper);
    }
}
